

class UsuarioController {

    def beforeInterceptor = [action:this.&auth, except:['login', 'autenticacao', 'logout']]

    def auth() {
        if (session.usuario) {
            if (session.usuario.nivelDeAcesso == Usuario.NIVEL_ADMINISTRADOR) return true
        }

        flash.message = "Você não está logado ou não tem permissão para visualizar essa página"
        redirect(controller:'usuario', action:'login')
        return false
    }

    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def list = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        [ usuarioInstanceList: Usuario.list( params ), usuarioInstanceTotal: Usuario.count() ]
    }

    def show = {
        def usuarioInstance = Usuario.get( params.id )

        if(!usuarioInstance) {
            flash.message = "Usuario not found with id ${params.id}"
            redirect(action:list)
        }
        else { return [ usuarioInstance : usuarioInstance ] }
    }

    def delete = {
        def usuarioInstance = Usuario.get( params.id )
        if(usuarioInstance) {
            try {
                usuarioInstance.delete()
                flash.message = "Usuario ${params.id} deleted"
                redirect(action:list)
            }
            catch(org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "Usuario ${params.id} could not be deleted"
                redirect(action:show,id:params.id)
            }
        }
        else {
            flash.message = "Usuario not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {
        def usuarioInstance = Usuario.get( params.id )

        if(!usuarioInstance) {
            flash.message = "Usuario not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            return [ usuarioInstance : usuarioInstance ]
        }
    }

    def update = {
        def usuarioInstance = Usuario.get( params.id )
        if(usuarioInstance) {
            if(params.version) {
                def version = params.version.toLong()
                if(usuarioInstance.version > version) {
                    
                    usuarioInstance.errors.rejectValue("version", "usuario.optimistic.locking.failure", "Another user has updated this Usuario while you were editing.")
                    render(view:'edit',model:[usuarioInstance:usuarioInstance])
                    return
                }
            }
            usuarioInstance.properties = params
            if(!usuarioInstance.hasErrors() && usuarioInstance.save()) {
                flash.message = "Usuario ${params.id} updated"
                redirect(action:show,id:usuarioInstance.id)
            }
            else {
                render(view:'edit',model:[usuarioInstance:usuarioInstance])
            }
        }
        else {
            flash.message = "Usuario not found with id ${params.id}"
            redirect(action:edit,id:params.id)
        }
    }

    def create = {
        def usuarioInstance = new Usuario()
        usuarioInstance.properties = params
        return ['usuarioInstance':usuarioInstance]
    }

    def save = {
        def usuarioInstance = new Usuario(params)
        if(!usuarioInstance.hasErrors() && usuarioInstance.save()) {
            flash.message = "Usuario ${usuarioInstance.id} created"
            redirect(action:show,id:usuarioInstance.id)
        }
        else {
            render(view:'create',model:[usuarioInstance:usuarioInstance])
        }
    }

    def login = { }

    def autenticacao = {

        def usuarioAtual = Usuario.findByEmailAndHashSenha(params.email, params.senha.encodeAsPassword())
        if(usuarioAtual) {
            session.usuario = usuarioAtual

            if(session.usuario.nivelDeAcesso.equals(Usuario.NIVEL_ADMINISTRADOR)) {
                render("Administrador")
            } else if(session.usuario.nivelDeAcesso.equals(Usuario.NIVEL_COORDENACAO)) {
                render("Coordenacao")
            } else if(session.usuario.nivelDeAcesso.equals(Usuario.NIVEL_PROFESSOR)) {
                render("Professor")
            } else if(session.usuario.nivelDeAcesso.equals(Usuario.NIVEL_ALUNO)) {
                print usuarioAtual
                def alunoLogado = Aluno.findByUsuario(usuarioAtual)
                print alunoLogado
                session.idAluno = alunoLogado.id
                session.aluno = alunoLogado
                redirect(controller:'aluno', action:'edit', id:alunoLogado.id)
            }


        } else {
            flash.message = "Desculpe, Usuário incorreto."
            redirect(action:"login")
        }

    }

    def logout = {
        flash.message = "Logout feito com sucesso"
        session.usuario = null
        redirect(uri:"/")
    }
}
